$(function () {
  // 创建编辑器
  let E = window.wangEditor;
  let editor = new E('#news-content');
  editor.create();

  // 上传图片
  let $thumbnailUrl = $("#news-thumbnail-url");
  /*======== 服务器版 =======*/
  let $uploadNew = $("#upload-news-thumbnail");
  // change 表单里面 select file 都会触发change事件
  $uploadNew.change(function () {
    //File{name: "acatar.jpg", lastModified: 1524893383820, lastModifiedDate: Sat Apr 28 2018 13:29:43 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 12173, …}
    // form
    let file = this.files[0];
    // 获取文件名字
    let fileName = file.name;
    // 创建一个 FormData
    let formData = new FormData();
    // 把"文件"添加进去
    formData.append("uploadFile", file);
    $.post({
      url: "/admin/upload-file/",
      // 数据就是 formData
      data: formData,
      // 这两个一定要写
      processData: false,
      contentType: false,
      success: res => {
        if (res["code"] === 0) {
          let thumbnailUrl = res["data"]["url"];
          $thumbnailUrl.val('');
          $thumbnailUrl.val(thumbnailUrl);
        }
      },
      error: err => {
        logErr(err);
      }
    })

  });

  /*=====  七牛版 ========*/
  let $progressBar = $(".progress-bar");
  fQiniu.upload({
    // 七牛空间域名
    "domain": "http://onj3s3zfw.bkt.clouddn.com/",
    // 后台返回 token的地址
    "uptoken_url": "/admin/up-token/",
    // 按钮
    "browse_btn": "upload-btn",
    // 成功
    "success": (up, file, info) => {
      // up: plupload.Uploader {id: "o_1cm86cpca1pghac2vdllbs18b71", uid: "o_1cm86cpca1pghac2vdllbs18b71", state: 2, features: {…}, runtime: "html5", …}
      // file: PluploadFile {id: "o_1cm86cu303gsslb101u1rbe4u77", name: "1.png", type: "image/png", size: 233127, origSize: 233127, …}

      // info {"hash":"Fsia2O16HSkqbDmYln8iw2yCqHAY","key":"o_1cm86cu303gsslb101u1rbe4u77.png"}
      let domain = up.getOption('domain');
      let res = JSON.parse(info);
      let filePath = domain + res.key;
      $thumbnailUrl.val('');
      $thumbnailUrl.val(filePath);
    },
    // 失败
    "error": (up, err, errTip) => {
      console.log('error');
      console.log(up);
      console.log(err);
      console.log(errTip);
      console.log('error');
    },
    // 上传文件的过程中 七牛对于 4M 秒传
    "progress": (up, file) => {
      let percent = file.percent;
      $progressBar.parent().css("display", 'block');
      $progressBar.css("width", percent + '%');
      $progressBar.text(parseInt(percent) + '%');
    },
    // 完成后 去掉进度条
    "complete": () => {
      $progressBar.parent().css("display", 'none');
      $progressBar.css("width", '0%');
      $progressBar.text('0%');
    }
  });

  // 获取元素
  let $NewsPub = $(".btn-pub-news");
  $NewsPub.click(function () {
    let titleVal = $("#news-title").val();
    let descVal = $("#news-desc").val();
    // 最简单  change/selected / checked
    let tagId = $("#news-category").val();
    let thumbnailVal = $thumbnailUrl.val();
    let contentHtml = editor.txt.html();
    let contentText = editor.txt.text();
    if(tagId === '0'){
      fAlert.alertInfoToast('请选择新闻标签')
    }
    // console.log(titleVal);
    // console.log(descVal);
    // console.log(tagId);
    // console.log(thumbnailVal);
    // console.log(contentHtml);
    // console.log(contentText);
    $.post({
      url: "/admin/news-pub/",
      data: {
        "title": titleVal,
        "desc": descVal,
        "tag_id": tagId,
        "thumbnail_url": thumbnailVal,
        "content": contentHtml,
      },
      success: res=>{
        // console.log(res);
        if(res["code"]===0){
          // {"text":"", }
          let news=res["data"];
          fAlert.alertNewsSuccessCallback("新闻发表成功", "查看新闻", ()=>{
            // 查看新闻
            window.location.href = `/news/detail/${news.news_id}`;
          })
        }else {
          fAlert.alertErrorToast(res["msg"]);
        }
      },
      error: err =>{
        logErr(err);
      }
    })
  });
});  



function logErr(err) {
  console.log(err);
  console.log(err.status + "===" + err.statusText);
}